/*
 * @Author: your name
 * @Date: 2021-06-26 21:07:06
 * @LastEditTime: 2021-06-27 15:31:49
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 */

import { find, Node, view } from "cc";
import { GComponent, GObject, GRoot } from "fairygui-cc";
import { LayerType } from "./LayerType";

export class LayerManager {

    private static _inst: LayerManager;
    static get inst() {
        if (this._inst) {
            return this._inst;
        }
        this._inst = new LayerManager();
        return this._inst;
    }

    private worldLayers!: { [key: number]: Node };
    private uiLayers!: { [key: number]: GComponent };

    private _root!: any;
    public get root(): Node {
        if (this._root == null)
            this._root = find("Canvas");
        return this._root;
    }

    public init() {
        if (this.worldLayers == null) {
            this.worldLayers = {};
            for (let i = 0; i <= LayerType.Game_View; ++i) {
                let node = new Node();
                node.name = "Layer" + i;
                this.root.addChild(node);
                this.worldLayers[i] = node;
            }
        }

        if (this.uiLayers == null) {
            this.uiLayers = {};
            GRoot.inst.node.setSiblingIndex(LayerType.MAX);
            for (let i = LayerType.Game_View + 1; i < LayerType.MAX; ++i) {
                let node = new GComponent();
                node.name = "Layer" + i;
                GRoot.inst.addChild(node);
                node.makeFullScreen();
                this.uiLayers[i] = node;
            }
        }

        let layer = this.uiLayers[LayerType.UI_Res];
        layer.visible = false;

        view.setResizeCallback(this.onResize.bind(this));
    }

    private onResize() {
        GRoot.inst.makeFullScreen();
        // for (let key in this.uiLayers) {
        //     this.uiLayers[key].makeFullScreen();
        // }
        for (let key in this.uiLayers) {
            this.uiLayers[key].makeFullScreen();
        }
    }


    public setLayer(node: GObject | Node, layer: LayerType) {
        if (node instanceof GObject) {
            this.uiLayers[layer].addChild(node);
        }
        else {
            if (layer <= LayerType.Game_View) {
                this.worldLayers[layer].addChild(node);
            }
            else {
                this.uiLayers[layer].node.addChild(node);
            }
        }
    }

    public getLayer(layer: LayerType): Node {
        if (layer <= LayerType.Game_View) {
            return this.worldLayers[layer];
        }
        else {
            return this.uiLayers[layer].node;
        }
    }
}